package com.cedifie.lendapp.ui.loan.fm

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.FmLoanRepayBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.MvpFm
import com.cedifie.lendapp.ui.loan.adapter.CedLoanRepayLableAdapter
import com.cedifie.lendapp.ui.loan.impl.CedLoanRepayPresenterImpl
import com.cedifie.lendapp.ui.loan.view.ICedLoanRepayView
import com.cedifie.lendapp.utils.decoration.LinearSpacingItemDecoration
import com.cedifie.lendapp.utils.event.CedEventManager
import com.cedifie.lendapp.utils.event.CedEventType
import com.lib.base.utils.DensityUtils
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import java.math.BigDecimal

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/17 13:41
 * @Annotation：待还款Page
 */
class CedLoanRepayFm(): MvpFm<ICedLoanRepayView, CedLoanRepayPresenterImpl>(),ICedLoanRepayView {

    private var _binding: FmLoanRepayBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "binding is null"
    )
    //还款明细
    private var lableAdapter: CedLoanRepayLableAdapter? = null

    override fun getCedRootView(inflater: LayoutInflater): View {
        _binding = FmLoanRepayBinding.inflate(inflater)
        return binding.root
    }

    override fun initCedView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))

        initCedRefreshLayout()
        initCedRepayRecyclerView()
    }

    override fun initCedListener() {
        //展开、收起
        _binding?.ivLable?.setOnClickListener {
            mvpPresenter?.onCedClickLableAction()
        }

        //还款
        _binding?.btnRepayment?.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_LOAN_REPAYMENT,"")
            //立即上报
            CedEventManager.getInstance().updateCedEventsNow()

            mvpPresenter?.loadCedPayLinkAction()
        }
    }

    override fun initCedData() {
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_LOAN_REPAYMENT_START,"")
        mvpPresenter?.onCedClickLableAction()
        showCedLoading(getString(R.string.loading))
        mvpPresenter?.loadCedLoanLimitAction()
    }

    override fun createMvpPresenter(): CedLoanRepayPresenterImpl {
        return CedLoanRepayPresenterImpl(context)
    }

    /* 初始化刷新 */
    private fun initCedRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            //发送刷新流程通知
            EventBus.getDefault().post(CedEventType.NOTICE.CED_PROCESS_REFRESH)
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 初始化列表
     */
    private fun initCedRepayRecyclerView() {
        _binding?.recyclerView?.setHasFixedSize(true)
        _binding?.recyclerView?.isNestedScrollingEnabled = false
        _binding?.recyclerView?.isFocusableInTouchMode = false //不需要焦点
        _binding?.recyclerView?.layoutManager = LinearLayoutManager(context)
        val topDecoration = DensityUtils.dp2px(20f)
        _binding?.recyclerView?.addItemDecoration(LinearSpacingItemDecoration(0,0,topDecoration,topDecoration))
        lableAdapter = CedLoanRepayLableAdapter(_binding?.recyclerView)
        _binding?.recyclerView?.adapter = lableAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        lableAdapter?.setOnItemChildClickListener { _, childView, _ ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        }
    }

    /**
     * 刷新还款信息
     */
    fun refreshAction(){
        mvpPresenter?.loadCedRepayInfoAction()
    }

    /**
     * 显示展开
     */
    override fun showCedOpenViews() {
        _binding?.recyclerView?.visibility = View.VISIBLE
        _binding?.vLine?.visibility = View.VISIBLE
        _binding?.ivLable?.setImageResource(R.mipmap.icon_loan_repay_up)
        HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_LOAN_REPAYMENT_INFO_OPEN,"")
    }

    /**
     * 显示收起
     */
    override fun showCedCloseViews() {
        _binding?.recyclerView?.visibility = View.GONE
        _binding?.vLine?.visibility = View.GONE
        _binding?.ivLable?.setImageResource(R.mipmap.icon_loan_repay_down)
        HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_LOAN_REPAYMENT_INFO_CLOSE,"")
    }

    /**
     * 展示还款信息
     */
    @SuppressLint("SetTextI18n")
    override fun showCedRepayInfo(data: JSONObject) {
        //总可借款额度
        val limitAmount = BigDecimal(data.optString("limitAmount")).stripTrailingZeros().toPlainString()
        //本次借款额度
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        //不显示百分比
        _binding?.circleSeekBar?.setShowPercentText(false)
        _binding?.circleSeekBar?.max = amount.toInt()
        _binding?.circleSeekBar?.labelText = amount
        //设置额度
        _binding?.circleSeekBar?.showAnimation(0, amount.toInt(), 1500)

        val repayAmount = BigDecimal(data.optString("repayAmount")).stripTrailingZeros().toPlainString()
        _binding?.textRepayAmount?.text = repayAmount
        _binding?.textRepayDate?.text = data.optString("repayDate")
        _binding?.textTotal?.text = "$repayAmount ${data.optString("currency")}"

        val array = data.optJSONArray("repayList")
        val dataList = arrayListOf<JSONObject>()
        if (array != null) {
            for (i in 0..<array.length()){
                dataList.add(array.optJSONObject(i))
            }
        }
        lableAdapter?.data = dataList
    }

    /**
     * 打开还款链接
     */
    override fun showCedPayLink(linkUrl: String) {
        if (linkUrl.isNotEmpty()){
            val uri = Uri.parse(linkUrl)
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        }
    }

    override fun hideCedLoading() {
        super.hideCedLoading()
        _binding?.refreshLayout?.finishRefresh()
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_LOAN_REPAYMENT_END,"")
        //立即上报
        CedEventManager.getInstance().updateCedEventsNow()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}